/*
 * @Date: 2022-02-14 12:00:49
 * @LastEditors: 春贰
 * @Desc:
 * @LastEditTime: 2023-11-08 14:58:38
 * @FilePath: \server\system\core\config\config.go
 */
package config

import (
	"io/ioutil"
	"log"

	"github.com/spf13/viper" //配置
	"go-easy-dashboard/system/common/initial"
	"go-easy-dashboard/system/util/file"
	"go-easy-dashboard/system/util/sys"
)

var c *conf

func Instance() *conf {
	if c == nil {
		basedir := sys.ExecutePath() + "\\" //根目录
		InitConfig(basedir + "config.toml")
	}
	return c
}

type conf struct {
	DB     DBConf
	App    AppConf
	Zaplog ZapLogConf
	Jwt    JwtConf
	Upload UploadConf
	Pdf    PdfConf
	Ldap   LdapConf
}

type DBConf struct {
	DBType     string
	DBUser     string
	DBPwd      string
	DBHost     string
	DBName     string
	DBloglevel string
}

type LdapConf struct {
	Host      string //"ldap://dcy.dcy:389"
	AdminUser string //"CN=Administrator,CN=Users,DC=dcy,DC=dcy"
	AdminPass string
	BaseDn    string //"dc=dcy,dc=com" ,域控登录的地址
}

type AppConf struct {
	Key       string
	HttpPort  int `json:"http-port"`
	HttpsPort int `json:"https-port"`
	WsPort    int
	WssPort   int
	Env       string
	Timeout   int
	PageSize  int
}

type JwtConf struct {
	JwtSecret   string
	BufferTime  int64
	ExpiresTime int64
	Issuer      string
}

type ZapLogConf struct {
	Director string ` json:"director"`
	Level    string ` json:"level" `
}

type UploadConf struct {
	Path      string   ` json:"path"`
	MaxSize   float64  ` json:"maxsize" `
	AllowType []string ` json:"allowtype" `
}

type PdfConf struct {
	ReplaceBefore []string ` json:"ReplaceBefore"`
	ReplaceAfter  []string ` json:"ReplaceAfter"`
}

func InitConfig(tomlPath ...string) {
	if len(tomlPath) > 1 {
		log.Fatal("配置路径数量不正确")
	}
	if file.CheckNotExist(tomlPath[0]) {
		err := ioutil.WriteFile(tomlPath[0], []byte(initial.ConfigToml), 0777)
		if err != nil {
			log.Fatal("无法写入配置模板", err.Error())
		}
		log.Fatal("配置文件不存在，已在根目录下生成示例模板文件【config.toml】，请修改后重新启动程序！")
	}
	v := viper.New()
	v.SetConfigFile(tomlPath[0])
	err := v.ReadInConfig()
	if err != nil {
		log.Fatal("配置文件读取失败: ", err.Error())
	}
	err = v.Unmarshal(&c)
	if err != nil {
		log.Fatal("配置解析失败:", err.Error())
	}
}
